<?php
namespace Mobile\Controller;
use Common\Tool\Tool;
use Mobile\Model\GoodsClassModel;
use Mobile\Model\GoodsModel;

//前台商品模块
class GoodsController extends BaseController{
	
	//商品分类
	public function goods_pagelist()
	{
	   //连接工具
	   Tool::connect('Tree');
	   //获取数据
	   $parentData = GoodsClassModel::getInition()->buildTreeData(array(
	        'field' => array('class_name', 'id', 'pic_url', 'fid'),
	        'where' => array('fid' => 0, 'hide_status' => 0, 'type' => 1),
	        'order' => 'create_time DESC, update_time DESC'
	    ));
	   $this->parentData = $parentData;
	   $this->display();
	}
	
	
	//商品列表
	public function goods_goodslist()
	{
	    //检测传值
	    Tool::checkPost($_GET, array('is_numeric' => array('class_id')), true, array('class_id')) ? true : $this->error('灌水机制已打开', U('Index/index'));
	    //获取相应的自己编号
	    $childrenId = GoodsClassModel::getInition()->getChildren(array(
	        'fid'          => $_GET['class_id'],
	        'type'         => 1,
	        'hide_status'  => 0
	    ), array(
	        'id','fid'
	    ));
	    $childrenId = empty($childrenId) ?  $_GET['class_id'] : $childrenId;
	    //设置排序默认值
        Tool::isSetDefaultValue($_GET, array('order'),'pre');	    
	    //传递数据到商品模型
	    $data = GoodsModel::getInitation()->searchGoods(array(
	        'field' => array('id', 'price_old', 'price_new', 'pic_url','title', 'fanli_jifen')
	    ), $childrenId, $_GET['order']);
		$this->finds = $data;
		$this->class_id = $_GET['class_id'];
		$this->display();
	}
	
	//商品页面
	public function goods_goods(){
	    
		$id = $_GET['id'];
		$pid = I('get.pid');
		cookie('mytuijianren',$pid,86400);
		$goods = M('goods');
		$resone = $goods->where('id='.$id)->find();
		
		//连接拼接引擎
		\Common\Tool\Tool::connect('Mosaic');
		$pic = unserialize($resone['pic_tuji']);
		//拼接路径
		$pic = \Common\Tool\Tool::MosaicPath($pic);
		$this->assign('pic',$pic);
		$this->assign('resone',$resone);
		$taocan = unserialize($resone['taocan']);
		$this->assign('taocan',$taocan);

		//限购代码
		$orders_record = M('goods_orders_record');
		$where_record['user_id'] = $_COOKIE['user_id'];
		$where_record['goods_id'] = $_GET['id'];
		$result_orders_record = $orders_record->where($where_record)->find();
		if(!empty($result_orders_record)){
			$this->assign('xiangou_yigoumai',1);	//限购已购买
		}

		//查询是否是用户身份代码
		$member = M('member','vip_');
		$where_m['id'] = $_COOKIE['user_id'];
		$res_member = $member->where($where_m)->find();
		$this->assign('res_member',$res_member);

		$m = M('goods_shoucang');
		$where_sc['user_id'] = $_COOKIE['user_id'];
		$where_sc['goods_id'] = $_GET['id'];
		$result_sc = $m->where($where_sc)->find();

		$this->assign('result_sc',$result_sc);

		$this->display();
	}
	//获取到用户自己的id供分享网址使用
	public function _before_goods_goods(){
		//exit;
		$id=I('id');//商品id
		//用户id
		if(session('user_id')!=null){
			$user_id=session('user_id');
		}elseif(cookie('user_id')!=null){
			$user_id=cookie('user_id');
		}elseif(cookie('userid')!=null){
			$user_id=cookie('userid');
		}else{
			$user_id=10000000;
		}
		if(!I('get.pid')){
			$this->redirect('Goods/goods_goods',array('id'=>$id,'pid'=>$user_id));
		 }
		
	}
	//商品详情
	public function goods_detail(){
		$where['id'] = $_GET['id'];
		$goods = M('goods');
		$resone = $goods->where($where)->find();
		$this->assign('resone',$resone);
		$this->display();
	}

	//商品详情 - 手机版
	public function goods_detail_m(){
		$where['id'] = $_GET['id'];
		$goods = M('goods');
		$resone = $goods->where($where)->find();
		$this->assign('resone',$resone);
		$this->display();
	}
	
	//商品评价
	public function goods_evaluate(){
		$id = $_GET['id'];
		$goods = M('goods');
		$resone = $goods->where('id='.$id)->find();
		$this->assign('resone',$resone);


		$pingjia = M('goods_orders_record');
		$where_pingjia['goods_id'] = $_GET['id'];
		$where_pingjia['pingjia_status'] = array('in',"1,2,3");
		$result_pingjia = $pingjia->where($where_pingjia)->order('pingjia_time DESC')->select();
		$this->assign('result_pingjia',$result_pingjia);
$this->assign('count',count($result_pingjia));

		$this->assign('list',$list);

		$this->display();
	}
	
	//添加商品足迹
	public function add_footprint(){
		if(IS_POST){
			$info = M('foot_print');
			$_POST['uid'] = $_COOKIE['userid'];
			$_POST['gid'] = I('gid');
			$_POST['goods_pic'] = I('goods_pic');
			$_POST['goods_name'] = I('goods_name');
			$_POST['goods_price'] = I('goods_price');
			$_POST['type'] = I('type');
			$_POST['create_time'] = time();
			$result = $info->where(array('uid'=>$_POST[uid],'gid'=>$_POST[gid]))->select();
			if(!empty($_COOKIE['userid'])){
				if(!$result){
					$info->add($_POST);
				}else{
					$info->where(array('uid'=>$_POST[uid],'gid'=>$_POST[gid]))->save($_POST);
				}
			}
		}
	}
	
	//商品添加购物车
	public function add_cart(){
		if(empty($_COOKIE['userid'])){
			//要回调的url
			$this->ajaxReturn(2);	//请先登录
		}
		$m = M('goods_cart');
		$where['user_id'] = $_COOKIE['userid'];
		$where['goods_id'] = $_POST['goods_id'];
		$where['taocan_name'] = $_POST['taocan_name'];

		$result = $m->where($where)->find();
		//购物车中无商品，添加一条新信息，购物车中已有信息，则数量 +1
		if(empty($result)){
			$_POST['user_id'] = $_COOKIE['userid'];
			$_POST['create_time'] = time();
			$result = $m->add($_POST);
		}else{
			$_POST['user_id'] = $_COOKIE['userid'];
			$_POST['update_time'] = time();
			$_POST['goods_num'] = $result['goods_num'] + 1;
			$where2['id'] = $result['id'];
			$result = $m->where($where2)->save($_POST);
		}
		if($result){
			$this->ajaxReturn(1);   //成功
		}else{
			$this->ajaxReturn(0);	//失败
		}
	}
	
	//购物车列表
	public function goods_cart(){
		

		if(empty($_COOKIE['userid'])){
			$this->redirect('User/login');	//请先登录
		}
		$m = M('goods_cart');
		$where['user_id'] = $_COOKIE['userid'];
		$result = $m->where($where)->select();
		$g = M('goods');
		foreach ($result as $k=>$v){
			$goods_id = $v['goods_id'];
			$res_price = M('goods')->field('title,price_new,price_old,pic_url')->where('id = '.$goods_id)->find();
			$result[$k]['price_new'] = $res_price['price_new'];
			$result[$k]['price_sum'] = $res_price['price_new'] * $v['goods_num'];
			$result[$k]['goods_title'] = $res_price['title'];
			$result[$k]['pic_url'] = $res_price['pic_url'];
			$result[$k]['price_new'] = $res_price['price_new'];
			$result[$k]['price_old'] = $res_price['price_old'];
		}
		$this->assign('result',$result);
		$count = count($result);
		$this->assign('count',$count);
		$this->display();
	}

	//商品立即购买-结算
	public function goods_count(){
		if(empty($_COOKIE['userid'])){
			$this->redirect('User/login');
		}else{
		//获得传递过来的数据 并且做相关的处理
		//判断是否是立即付款
			if($_POST['now_buy'] == 1){
				$price_sum = $_POST['price_sum'];
				$goods_data = array();
				$goods_data[0]['goods_title'] = $_POST['goods_title'][0];
				$goods_data[0]['goods_id'] = $_POST['goods_id'];
				$goods_data[0]['pic_url'] = $_POST['pic_url'][0];
				$goods_data[0]['goods_num'] = $_POST['goods_num'][0];
				$goods_data[0]['price_new'] = $_POST['price_new'][0];
				$goods_data[0]['taocan_name'] = $_POST['taocan_name'];
				$goods_data[0]['fanli_jifen'] = $_POST['fanli_jifen'];

			}else{
				//购物车中购买，过滤提交的数据

				foreach ($_POST['hidden_xuanze'] as $k=>$v){
					if($v == 1){	//过滤选中的商品ID
						$goods_data[$k]['goods_id'] = $_POST['goods_id'][$k];	//商品ID
						$goods_data[$k]['goods_num'] = $_POST['goods_num'][$k];	//商品数量
						$goods_data[$k]['pic_url'] = $_POST['pic_url'][$k];	//商品图片
						$goods_data[$k]['goods_title'] = $_POST['goods_title'][$k];	//商品名称
						$goods_data[$k]['price_new'] = $_POST['price_new'][$k];  	//商品的单价
						$goods_data[$k]['taocan_name'] = $_POST['taocan_name'][$k];  	//套餐名称     
						$goods_data[$k]['fanli_jifen'] = $_POST['fanli_jifen'][$k];  	//返利积分
						$price_arr[] =$_POST['price_new'][$k] * $_POST['goods_num'][$k];
					}
				}

				$price_sum = array_sum($price_arr);		//计算价格之和
			}

//dump($goods_data);

			//判断post过来的数据是否存在
			if(!empty($goods_data)){
				$_SESSION['price_sum'] = $price_sum;
				$_SESSION['goods_data'] = $goods_data;	//选中的商品数据临时存储在session中
			}
			/*dump($_SESSION['price_sum']);*/
			//dump($goods_data['goods_id']);exit;
			$this->assign('price_sum',$_SESSION['price_sum']);	//合计金额
			$this->assign('goods_data',$_SESSION['goods_data']);	//选择的商品
			//判断是否是微信浏览器
			if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')!== false ){//是
				$weixin['isok'] = 1;
			}else{
				$weixin['isok'] = 2;
			}
			
			//dump($_POST['type']);
		
			
			$this->assign('order_type',$_POST['type']);
			$this->assign('weixin',$weixin);
			//选择地址
			$userid = $_COOKIE['userid'];
			/**查询积分账户余额**/
			$my=M('user')->where(array('id'=>$userid))->find();
			$this->assign('jfa',$my['add_jf_limit']);
			$this->assign('jfb',$my['add_jf_currency']);
			/**查询用户等级**/
			$grade=M('member','vip_')->where(array('id'=>$userid))->getField('grade_name');
			$this->assign('grade',$grade);
			$where['user_id'] = $userid;
			if(I('get.address_id')){
				$find_address = M('user_address')->where(array('id'=>I('get.address_id')))->find();
			}else{
				$where['status'] = 1;
				$this->assign('weixin',$weixin);
				$find_address = M('user_address')->where($where)->find();
				if(empty($find_address)){
					$find_address = M('user_address')->where(array('user_id'=>$userid))->find();
				}
			}
			$this->assign('weixin',$weixin);
			$youfei=$this->count_freight($goods_data,$find_address["prov"]);
			$zongjia=$_SESSION['price_sum']+$youfei;
			$this->assign('zongjia',$zongjia);
			$this->assign('youfei',$youfei);
			$this->assign('find',$find_address);
			$this->display();
			// 收货地址切换备份
			/**
			$where['user_id'] = $userid;
			$this->assign('weixin',$weixin);
			$res_addr_alone = M('user_address')->where($where)->find();
			 $youfei=$this->count_freight($goods_data,$res_addr_alone["prov"]);
			$zongjia=$_SESSION['price_sum']+$youfei;
			$this->assign('zongjia',$zongjia);
			$this->assign('youfei',$youfei);
			$this->assign('find',$res_addr_alone);
			$this->display();
			**/
			
		}
	}

	/*
	 * 手机端形成订单
	 */


	
	 /*下单成功后的页面*/
    public function make_pay_button(){
        require_once("./alipaymobile/alipay.config.php");
        require_once("./alipaymobile/lib/alipay_submit.class.php");

        /**************************请求参数**************************/
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = I('get.orders_num');
        //订单名称，必填
        $subject = I('get.orders_num');
       /* $goods_orders = M('Goods_orders');
        $res = $goods_orders->field('price_sum')->where('orders_num='.$subject)->find();
        //付款金额，必填
        $total_fee = $res['price_sum'];*/
         //这个位置要更具订单号判断到底是商品旅游支付 还是会员充值

        $info_a = strpos($out_trade_no,'u');

        if($info_a==1){
            $info = M('User_huifei')->field('hf_money')->where(array(
                'orders_num'=>$out_trade_no
            ))->find();
            $price_sum = $info['hf_money'];
        }else{
            $goods_orders = M('Goods_orders');
            $info = $goods_orders->field('price_sum')->where(array(
                'orders_num'=>$out_trade_no
            ))->find();
            $price_sum = $info['price_sum'];
        }


        //付款金额，必填
        $total_fee =$price_sum;
      // $total_fee =0.01;
        //商品描述，可空
        $body = '';

        /************************************************************/
//构造要请求的参数数组，无需改动
        $parameter = array(
            "service"       => $alipay_config['service'],
            "partner"       => $alipay_config['partner'],
            "seller_id"  => $alipay_config['seller_id'],
            "payment_type"	=> $alipay_config['payment_type'],
            "notify_url"	=> $alipay_config['notify_url'],
            "return_url"	=> $alipay_config['return_url'],

            "anti_phishing_key"=>$alipay_config['anti_phishing_key'],
            "exter_invoke_ip"=>$alipay_config['exter_invoke_ip'],
            "out_trade_no"	=> $out_trade_no,
            "subject"	=> $subject,
            "total_fee"	=> $total_fee,
            "body"	=> $body,
            "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
            //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.kiX33I&treeId=62&articleId=103740&docType=1
            //如"参数名"=>"参数值"

        );
//建立请求
        $alipaySubmit = new \AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
        echo $html_text;

    }
    /*服务器异步通知页面路径 */
    public function pay_responsed(){
        require_once("./alipaymobile/alipay.config.php");
        require_once("./alipaymobile/lib/alipay_notify.class.php");

//计算得出通知验证结果
        $alipayNotify = new \AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();

        if($verify_result) {//验证成功
            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];
            //支付宝交易号
            $trade_no = $_POST['trade_no'];

            //交易状态
            $trade_status = $_POST['trade_status'];

            if($_POST['trade_status'] == 'TRADE_FINISHED') {
               
            }
            else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
				 //进行自己的数据库的状态的修改
                /*$data = array();
                $data['pay_status'] = 1;
                $data['pay_time'] = time();
                M('Goods_orders')->where('orders_num='.$out_trade_no)->save($data);*/
                $orders_num =$out_trade_no;
                $info_a = strpos($orders_num,'u');
                if($info_a==1){
                    $data = array();
                    $data['pay_status'] =1;
                    $data['pay_time'] = time();
                    $user_huifei = M('User_huifei');
                    $user_huifei->where(array('orders_num'=>$orders_num))->save($data);
					$user_huifei->where(array('orders_num'=>$orders_num))->setInc('use_times',1);
                    $res = $user_huifei->field('user_id,hf_money,use_times')->where(array('orders_num'=>$orders_num))->find();
                    $user_id = $res['user_id'];
                    $huifei_sum = $res['hf_money'];
                    /************/
					$admin=M('admin','vip_');
					$user=M('user');
					$my=$user->where(array('id'=>$user_id))->find();
					$arr['account']=$my['mobile'];
					$arr['password']=$my['password'];
					$arr['create_time']=NOW_TIME;
					$arr['status']=1;
					$admin_id=$admin->add($arr);
					$auth_group_access=M('auth_group_access','vip_');
					$auth_group_access->add(array('uid'=>$admin_id,'group_id'=>51));
					$user->where(array('id'=>$user_id))->save(array('admin_id'=>$admin_id));
					$map = array();
					$year=date("Y",NOW_TIME);
					$month=date("m",NOW_TIME);
					if($res['use_times']==1){
						if($huifei_sum==365){
						$map['grade_name'] ='会员';
						R('Award/vipLogic',array($user_id,$year,$month));
						$map['vip_end'] =NOW_TIME-0+31536000;
						}else if($huifei_sum==30000){
							R('Award/sVipLogic',array($user_id,array($year,$month)));
							$map['grade_name'] ='合伙人';
						}
						$map['admin_id'] =$admin_id;
						$map['status'] =1;
						$m = M('member','vip_');
						$m->where(array('user_id'=>$user_id))->save($map);
					}
					
					
					/*************/
                }else{
                    $data = array();
                    $data['pay_status'] = 1;
                    $data['pay_time'] = time();
                    M('Goods_orders')->where(array(
                        'orders_num'=>$orders_num
                    ))->save($data);
                }


            }

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

            echo "success";		//请不要修改或删除
        }
        else {
            //验证失败
            echo "fail";
        }
    }

    /*
     *页面跳转同步通知页面路径
     * 支付宝支付成功后跳到那个页面
     */
    public function pay_success_to(){
        $this->display();
    }
	
	

	public  function  make_order(){
		//dump($_POST);
		
		/***************************判断积分是否为负数或者超额使用**********************************/
		$usermodel=M('user');
		$my=$usermodel->where(array('id'=>cookie('userid')))->find();
		//dump($usermodel->getLastSql());
		$jfa=I('post.jfa');
		$youfei=I('post.yunfei');
		$jfa=floatval($jfa);
		$jfb=I('post.jfb');
		$jfb=floatval($jfb);
		if($jfa<0 || $jfb<0){
			$this->error('积分不能为负数');
			exit;
		}
		if($my['grade_name']=="合伙人"){
			//合伙人只判断B账户
			if($jfb>$my['add_jf_currency']){
            $this->error('积分账户不足'.$jfb);
			exit;
			}else{
				$data['use_jf_limit']=0;
				$data['use_jf_currency']=$jfb;
			}
        }else{
			//会员两个账户都要判断
			if($jfa>$my['add_jf_limit']){
            $this->error('积分A账户不足'.$jfa);
			exit;
			}
			if($jfb>$my['add_jf_currency']){
            $this->error('积分B账户不足'.$jfb);
			exit;
			}
			$data['use_jf_limit']=$jfa;
			$data['use_jf_currency']=$jfb;
		}
		if($jfa+$jfb>I('post.price_sum')){
			$this->error('亲,你花费的积分超过了商品总额了哦!');
		}
		/************************************************************************************************/
		$goods_orders = M('Goods_orders');
		$user_address = M('User_address');
		$data =array();
		$res_address = $user_address->where(array('id'=>$_POST['address_id']))->find();
		$data['user_address'] = $res_address['prov'].$res_address['city'].$res_address['dist'].$res_address['address'];
		//dump($res_address);
		$orders_num = time().sprintf("%06s",cookie('userid'));
		session('orders_num',$orders_num);
		$data['user_id'] = cookie('userid');
		$data['orders_num'] = session('orders_num');
		$data['price_sum'] = I('post.price_sum')-($jfa+$jfb);//***********************************待修改
		/**************收集用户积分***************/
		$data['yunfei']=$youfei;
		$data['use_jf_currency']=$jfb;
		$data['use_jf_limit']=$jfa;
		/***************************/
		$data['realname'] = $res_address['realname'];
		$data['mobile'] = $res_address['mobile'];
		$data['create_time'] = time();
		
		$aa['orders_num'] = $data['orders_num'];		
		$aa = $goods_orders->where($aa)->find();		
		if(empty($aa)){
			$info = $goods_orders->add($data);
			$goods_orders_id = $goods_orders->getLastInsID();
		}else{
			$info['id'] = $aa['id'];
			$goods_orders_id = $info['id'];
		}
		
		if($info){
			/**************扣除用户积分***************/
			$usermodel->where(array('id'=>$my['id']))->setDec('integral',$jfa+$jfb);
			$usermodel->where(array('id'=>$my['id']))->setDec('add_jf_currency',$jfb);
			$usermodel->where(array('id'=>$my['id']))->setDec('add_jf_limit',$jfa);
			/***************************/
			$map = array();
			foreach($_POST['goods_id'] as $k=>$v){
				$map[$k]['goods_id'] = $_POST['goods_id'][$k];
				$map[$k]['goods_title'] = $_POST['goods_title'][$k];
				$map[$k]['goods_num'] = $_POST['goods_num'][$k];
				$map[$k]['price_new'] = $_POST['price_new'][$k];
				$map[$k]['user_id'] = $_COOKIE['userid'];
				$map[$k]['pic_url'] = $_POST['pic_url'][$k];
				$map[$k]['taocan_name'] = $_POST['taocan_name'][$k];
				$map[$k]['fanli_jifen'] = $_POST['fanli_jifen'][$k];
				$map[$k]['goods_orders_id'] =$goods_orders_id;
				$map[$k]['create_time'] = time();
			}
			$goods_orders_record = M('Goods_orders_record');
			$info_a = $goods_orders_record->addAll($map);
			
			//计算返利积分
			$fanli_jf=0;
			$goods=M('goods');
			$good_ids=$goods_orders_record->field('goods_id,goods_num')->where(array('goods_orders_id'=>$goods_orders_id))->select();
			foreach($good_ids as $k=>$v){
				$jf=$goods->where(array('id'=>$v['goods_id']))->getField('fanli_jifen');
				$jf_sum=$jf*$v['goods_num'];
				$fanli_jf+=$jf_sum;
				$jf=0;
			}
			$goods_orders->where(array('id'=>$goods_orders_id))->save(array('fanli_jifen'=>$fanli_jf));
			
			
			if($info_a){
				$user_agent = $_SERVER['HTTP_USER_AGENT'];
				if (strpos($user_agent, 'MicroMessenger') === false) {
					// 非微信浏览器禁止浏览
					
					$this->redirect('Mobile/Tourism/mobile_pay_money',array('orders_num'=>$orders_num));
				} else {
					// 微信浏览器，允许访问
					
					session('orders_num',$orders_num);
					$this->redirect('Mobile/Wxpay/new_pay');
				}
			}

		}

	}








	
	//选择地址
	public function choose_address(){
		if(empty($_COOKIE['userid'])){
			$this->redirect('User/login');
		}else{
			$m = M('user_address');
			$where['user_id'] = $_COOKIE['userid'];
			$result = $m->where($where)->select();
			$this->assign('result',$result);
			$this->display();
		}
	}
	
	//商品立即购买-结算-添加地址
	public function address_add(){
		if(empty($_COOKIE['userid'])){
			$this->redirect('User/login');
		}else{
			if(!empty($_POST)){
				$m = M('user_address');
				$_POST['user_id'] = $_COOKIE['userid'];
				$_POST['create_time'] = time();
				if(!empty($_POST['status'])){
					$_POST['status'] = 1;
				}else {
					//把默认地址全部设置为非默认
					$data['status'] = 0;
					$m->where('user_id='.$_COOKIE['userid'])->save($data);
				}
				if($m->add($_POST)){
					$this->redirect('Goods/choose_address');
				}else{
					$this->error('添加失败');
				}
			}else{
				$this->display();
			}
		}
	}
	
	//清空购物车
	public function empty_cart(){
		if(empty($_COOKIE['userid'])){
			$this->redirect('User/login');
		}else{
			$userid = $_COOKIE['userid'];
			$delete_all = M('goods_cart')->where('user_id='.$userid)->delete();
			$this->redirect('Goods/goods_cart');
		}
	}
	
	//删除购物车中单个商品
	public function del_onecart(){
		if(empty($_COOKIE['userid'])){
			$this->redirect('User/login');
		}else{
			$where['user_id'] = $_COOKIE['userid'];
			$where['id'] = $_POST['id'];
			$delete_one = M('goods_cart')->where($where)->delete();
			if($delete_one){
				$this->ajaxReturn(1);
			}else{
				$this->ajaxReturn(2);
			}
		}
	}
	
	//更新购物车数量
	public function update_goods_num(){
		$m = M('goods_cart');
		$where['id'] = $_GET['id'];
		$result = $m->where($where)->save($_GET);
		if($result){
			$this->ajaxReturn(1);
		}else {
			$this->ajaxReturn(0);
		}
	}
	
	/**
     * @param $goods 商品id和数量的组合(二维数组)
     * @param $area  省份名字
     * $goods,$area
     * 数组示例: $goods=array(
     * 0=>array('id'=>1,'num'=>2),
     * 1=>array('id'=>1,'num'=>3)
     * );
     * 省份名字示例: $area='河北省';
     */
    function count_freight($goods, $area){
		
		$baoyou_area = array('江苏省','浙江省','上海市','安徽省');//江浙沪皖包邮
        $goodsmodel = M('Goods');
		$areamodel = M('Region');
        $fregihtmodel = M('Freight');
		$yunfei = 0;
		//dump($goods);
		if($goods){
			$_SESSION['goods_info'] = $goods;
		}
		if(empty($goods) && !empty($_SESSION['goods_info'])){
			$goods = $_SESSION['goods_info'];
			//unset($_SESSION['goods_info']);
		}
		//dump($goods);
		//dump($area);
        foreach ($goods as $goodsrow) {
			$zhongliang = 0;
            $row = $goodsmodel->where(array('id' => $goodsrow['goods_id']))->find();
			//dump($row);
			//exit;
            $subject = $row['zhongliang'];
            $pattern = '/^\d+g$/';
            $patterns = '/^\d+g\*\d$/';
            preg_match($pattern, $subject, $matches);
            preg_match($patterns, $subject, $matche);

            if (!empty($matches) || !empty($matche)) {
                
                $row['zhongliang'] = str_replace('g', '', $row['zhongliang']);
                $a = explode('*', $row['zhongliang']);
                $rst = 1;
                foreach ($a as $k) {
                    $rst *= $k;
                }
                if (($row['min_yunfei'] != 0) || ($row['is_baoyou'] == 0)) {//如果其他地方不包邮或者江浙沪皖不包邮,则算出重量，方便计费
					$zhongliang += $rst * $goodsrow['goods_num'];
                }
				if($row['is_baoyou'] == 1){//	即使上面有运费，如果江浙沪皖包邮，则直接将重量设置为0，下面计算运费就直接返回0
					if(in_array($area,$baoyou_area)){
						$zhongliang=0;
					}
				}
            }
			
			$areaid = $areamodel->where(array('name' => $area))->find();
			$data = $fregihtmodel->where(array('province' => $areaid['areaid']))->find();
			//dump($fregihtmodel->getLastSql());
			 if($zhongliang==0){
				$yunfei+= 0;
			}else{
			if ($data['ykg'] == 3) {
				if ($zhongliang <= 3000) {
					$yunfei+= $data['money'];
				} else {
					$zhongliang = $zhongliang - 3000;//超出的部分
					$times = ceil($zhongliang/1000);//算出整数的公斤数
					$yunfei+= ($data['money']+$data['onemoney']*$times);
				}
			} else {
				if ($zhongliang <= 1000) {
					$yunfei+= $data['money'];
				} else {
					$zhongliang = $zhongliang - 1000;//超出的部分
					$times = ceil($zhongliang/1000);//算出整数的公斤数
					$yunfei+= ($data['money']+$data['onemoney']*$times);
				}
			}
			}
			
        }
		return $yunfei;
    }
}